//
//  FindViewController.m
//  
//
//  Created by 郭明皓 on 15/10/24.
//
//

#import "FindViewController.h"
#import <AFNetworking.h>
#import <UIImageView+WebCache.h>
#import <MJRefresh.h>
#import "GMHFindmodel.h"
#import "FindTableViewCell.h"
#import "GMPathCell.h"
#import "FinddetailViewController.h"
#import "GMCitys.h"
#import "GMHPath.h"
#import "FindPathSecondViewController.h"
#import "GMHHeaderCollectionReusableView.h"
#import "GMHDataFiled.h"
#import "GMHDataFiled.h"
#import <Reachability.h>
#import "MBProgressHUD.h"
#import "DKNightVersion.h"
#import "GMH_Share.h"
#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height
@interface FindViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate>
@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)UICollectionView *collectionView;
@property (nonatomic, retain)UICollectionViewFlowLayout *flow;
@property (nonatomic, retain)UIScrollView *scrollView;
@property (nonatomic, retain)UIScrollView *littleScrollView;
@property (nonatomic, retain)UISegmentedControl *segment;

@property (nonatomic, retain)NSMutableArray *findArr;
@property (nonatomic, retain)NSMutableArray *areaArr;
@property (nonatomic, retain)NSMutableArray *detailAreaArr;

@property (nonatomic, assign)BOOL isUpPull;
@property (nonatomic, assign)int pageIndex;
@property (nonatomic, assign)NSInteger flag;
@property (nonatomic, assign)UIButton *buttons;
@end

@implementation FindViewController
- (void)dealloc
{
    [_littleScrollView release];
    [_segment release];
    [_scrollView release];
    [_buttons release];
    [_findArr release];
    [_tableView release];
    [super dealloc];
}
- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.collectionView reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"发现美好";
    
    self.navigationItem.backBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil] autorelease];
    self.navigationController.navigationBar.nightBarTintColor = UIColorFromRGB(0x444444);
    
    
    self.segment = [[UISegmentedControl alloc]initWithItems:@[@"专题", @"路线库"]];
    self.segment.frame = CGRectMake(0, 64, self.view.frame.size.width, 40);
    [self.view addSubview:_segment];
    [_segment release];
    [_segment addTarget:self action:@selector(segment:) forControlEvents:UIControlEventValueChanged];
    _segment.selectedSegmentIndex = 0;
//    _segment.nightBackgroundColor = UIColorFromRGB(0x444444);
    

    
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 104, WIDTH, self.view.frame.size.height - 148)];
    [self.view addSubview:self.scrollView];
    [self.scrollView release];
    self.scrollView.contentSize = CGSizeMake(2 * WIDTH, 0);
    self.scrollView.pagingEnabled = YES;
    self.scrollView.delegate = self;
    if ([GMH_Share SingleShare].isNight == NO) {
        self.collectionView.backgroundColor = [UIColor whiteColor];
    }

    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.translucent = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    self.findArr = [NSMutableArray array];
        
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.scrollView.frame.size.height + 44) style:UITableViewStylePlain];
    [self.scrollView addSubview:self.tableView];
    [_tableView release];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 200;
    
    self.flow = [[UICollectionViewFlowLayout alloc]init];
    self.flow.itemSize = CGSizeMake(WIDTH / 4, HEIGHT / 5);
    self.flow.minimumLineSpacing = 10;//行间距
    self.flow.minimumInteritemSpacing = 2;//列间距
    self.flow.sectionInset = UIEdgeInsetsMake(WIDTH / 30, WIDTH / 30, WIDTH / 30, WIDTH / 30);
    self.flow.headerReferenceSize = CGSizeMake(200, 20);
    
    
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(WIDTH, 0, self.view.frame.size.width, self.scrollView.frame.size.height) collectionViewLayout:self.flow];
    [self.scrollView addSubview:self.collectionView];
    [self.collectionView release];
    
    
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[GMPathCell class] forCellWithReuseIdentifier:@"collectionView"];
    [self.collectionView registerClass:[GMHHeaderCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];

    
    if ([self isConnectionAvailable]) {
        [self DownPull];
        [self UpPull];
    }
    else
    {
        NSLog(@"没有网络时");
        //1.找沙盒路径
        NSString *sandboxpath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        //2.拼接电影的文件夹
        NSString *movieFile = [sandboxpath stringByAppendingPathComponent:@"Travel"];
        //3.创建一个文件管理者
        NSFileManager *manager = [NSFileManager defaultManager];
        //通过管理者调用方法,根据路径判断文件夹是否存在
        if (![manager fileExistsAtPath:movieFile]) {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];//<span style="font-family: Arial, Helvetica, sans-serif;">MBProgressHUD为第三方库，不需要可以省略或使用AlertView</span>
            hud.removeFromSuperViewOnHide =YES;
            hud.mode = MBProgressHUDModeText;
            hud.labelText = @"当前网络不可用，请检查网络连接";  //提示的内容
            hud.minSize = CGSizeMake(132.f, 58.0f);
            [hud hide:YES afterDelay:3];
        }
        else
        {

        //专题栏
        NSString *sendBoxPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
        NSString *CachesPath = [sendBoxPath stringByAppendingPathComponent:@"Travel/Find/home.plist"];
        NSDictionary *findDic = [NSKeyedUnarchiver unarchiveObjectWithFile:CachesPath];
        self.findArr = [GMHFindmodel baseModelArry:findDic[@"content"][@"themeList"] ];
        
        //路线库
        NSString *sendBoxPaths = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
        NSString *TravelPaths = [sendBoxPaths stringByAppendingPathComponent:@"Travel/Find/TravelPath.plist"];
        NSDictionary *travelDic = [NSKeyedUnarchiver unarchiveObjectWithFile:TravelPaths];
        self.areaArr = [GMHPath baseModelArry:travelDic[@"regions"]];

        }
    }

    
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (self.scrollView.contentOffset.x == 0) {
        _segment.selectedSegmentIndex = 0;
    }
    if (self.scrollView.contentOffset.x == WIDTH) {
        _segment.selectedSegmentIndex = 1;
    }
}
- (void)segment:(UISegmentedControl *)segment
{
    switch (segment.selectedSegmentIndex) {
        case TravelPath:

            self.scrollView.contentOffset = CGPointMake(0, self.scrollView.contentOffset.y);
             self.segment.selectedSegmentIndex = 0;
            break;
        case Toptic:
            //创建collectionView
            
            self.scrollView.contentOffset = CGPointMake(WIDTH, self.scrollView.contentOffset.y);
            _segment.selectedSegmentIndex = 1;
            break;
            
        default:
            break;
    }
}
- (void)DownPull
{
    __block FindViewController *find = self;
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{\
        [self.tableView.footer endRefreshing];
        self.pageIndex = 1;
        self.isUpPull = NO;
        [find create];
    }];
    [self.tableView.header beginRefreshing];
}
- (void)UpPull
{
    __block FindViewController *find = self;
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.pageIndex++;
        self.isUpPull = YES;
        [find create];
    }];
}
- (void)create
{
    [GMHDataFiled isHaveFileDocument];
    [GMHDataFiled isHaveFileFind];
    //专题数据
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *strurl = [NSString stringWithFormat:@"http://apiphp.yaochufa.com/portal/theme/areaThemeList?system=android&pageIndex=%d&cityCode=210200&channel=xiaomimarket&pageSize=20&imei=ffffffff-9317-02f2-ffff-fffff60c2478&regId=060dc37cc2d&version=4.3.1&deviceToken=ffffffff-9317-02f2-ffff-fffff60c2478", _pageIndex];
    if (self.isUpPull == NO) {
        [self.findArr removeAllObjects];
    }
    [manager GET:strurl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        NSMutableArray *arry = [GMHFindmodel baseModelArry:dic[@"content"][@"themeList"] ];
        [self.findArr addObjectsFromArray:arry];
        
        self.flag = self.findArr.count;
        if (_findArr.count > 0) {
            [self.tableView.header endRefreshing];
            [self.tableView.footer endRefreshing];
            [self.tableView reloadData];
        }
        
        
        NSString *sendBoxPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
        NSString *CachesPath = [sendBoxPath stringByAppendingPathComponent:@"Travel/Find/home.plist"];
        [NSKeyedArchiver archiveRootObject:dic toFile:CachesPath];
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"发现失败");
    }];
    //路线库数据
    NSString *collectionStr = @"http://tubu.ibuzhai.com/rest/v2/trail/regions?&device_type=2&app_version=4.3.4&api_version=1";
    [manager GET:collectionStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dics = responseObject;
        self.areaArr = [GMHPath baseModelArry:dics[@"regions"]];
        
        [self.collectionView reloadData];
        
        NSString *sendBoxPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
        NSString *CachesPath = [sendBoxPath stringByAppendingPathComponent:@"Travel/Find/TravelPath.plist"];
        [NSKeyedArchiver archiveRootObject:dics toFile:CachesPath];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"collectionview数据失败");
    }];
}
#pragma mark tableview协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.findArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *strs = @"tableView";
    FindTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strs];
    if (!cell) {
        cell = [[FindTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strs];
    }
    if (self.findArr.count != 0) {
        GMHFindmodel *find = self.findArr[indexPath.row];
        [cell.images sd_setImageWithURL:[NSURL URLWithString:find.imageUrl]placeholderImage:[UIImage imageNamed:@"travel.jpg"]];
        cell.titleLable.text = find.title;
        cell.descLabel.text = find.subTitle;
        cell.area.text = find.districtName;
        tableView.separatorStyle = UITableViewCellSelectionStyleNone;
        
    }
    return  cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
     self.tabBarController.tabBar.hidden = YES;
    [tableView deselectRowAtIndexPath:indexPath animated:YES];//点击后不显示效果
    FinddetailViewController *detail = [[FinddetailViewController alloc]init];
    [self.navigationController pushViewController:detail animated:YES];
    [detail release];
    
    GMHFindmodel *find = self.findArr[indexPath.row];
    detail.tagId = find.themeId;
}

#pragma  mark collectionView协议方法
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        GMHHeaderCollectionReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
        GMHPath *path = self.areaArr[indexPath.section];
        reusableView.label.text = [NSString stringWithFormat:@"◉%@", path.region];
        return reusableView;
    }
    return nil;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return  self.areaArr.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    GMHPath *path = self.areaArr[section];
    
    return path.province.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    GMPathCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionView" forIndexPath:indexPath];
        cell.contentView.backgroundColor = [UIColor cyanColor];

    NSDictionary *dic = [self.areaArr[indexPath.section] province] [indexPath.row];
    cell.backgroundColor = [UIColor clearColor];
    [cell.imagesView sd_setImageWithURL:[NSURL URLWithString:dic[@"icon"]]placeholderImage:[UIImage imageNamed:@"travel.jpg"]];
    cell.paths.text = [NSString stringWithFormat:@"路线%@", dic[@"trail_count"]];
    
    
    if ([GMH_Share SingleShare].isNight == YES) {
        self.collectionView.backgroundColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1];
    } else {
        self.collectionView.backgroundColor = [UIColor whiteColor];
    }
    return cell;
}
//collectionview点击
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.tabBarController.tabBar.hidden = YES;
    if ([GMH_Share SingleShare].isNight == YES) {
        
        
    }
    FindPathSecondViewController *pathSecond = [[FindPathSecondViewController alloc]init];
    [self.navigationController pushViewController:pathSecond animated:YES];
    [pathSecond release];
    NSDictionary *dic = [self.areaArr[indexPath.section] province] [indexPath.row];
    pathSecond.provinceName = dic[@"keyword"];
    NSLog(@"%@", pathSecond.provinceName);
    
}
//判断是否有网络
-(BOOL) isConnectionAvailable{
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = NO;
            //NSLog(@"notReachable");
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = YES;
            //NSLog(@"WIFI");
            break;
        case ReachableViaWWAN:
            isExistenceNetwork = YES;
            //NSLog(@"3G");
            break;
    }
    
    if (!isExistenceNetwork) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];//<span style="font-family: Arial, Helvetica, sans-serif;">MBProgressHUD为第三方库，不需要可以省略或使用AlertView</span>
        hud.removeFromSuperViewOnHide =YES;
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"当前网络不可用，请检查网络连接";  //提示的内容
        hud.minSize = CGSizeMake(132.f, 58.0f);
        [hud hide:YES afterDelay:1];
        return NO;
    }
    
    return isExistenceNetwork;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
